<template>
  <div class="common-layout">
    <el-container>
      <el-header class="navbar">
        <div class="navbar-wrapper">
          <div class="header-container">
            <div class="web-name">视频翻译器（Video Translator）</div>
            <div class="web-dis">
              <p>
                - 翻译/下载视频及脚本拆解（AI Translate/Download Videos and
                Scripts）
              </p>
            </div>
          </div>
          <div class="text-gray-light">
            <el-popover placement="bottom-end" :width="400">
              <template #reference>
                <div>我的积分 / My Points（{{ action.point }}）</div>
              </template>
              <el-table :data="action.pointLogs">
                <el-table-column width="150" property="createTime" label="Date"
                  ><template #default="scope">{{
                    scope.row.createTime.split(" ")[0]
                  }}</template></el-table-column
                >
                <el-table-column width="100" property="points" label="Point" />
                <el-table-column width="150" property="notes" label="Notes" />
              </el-table>
            </el-popover>
          </div>
        </div>
      </el-header>
      <el-main class="page-content" v-loading="action.isLoading">
        <client-only>
          <div class="in-input">
            <el-form
              ref="formRef"
              style="max-width: 800px"
              :model="ajaxForm"
              label-width="auto"
              class="demo-ruleForm"
              :rules="rules"
            >
              <el-form-item label="" prop="url">
                <el-input
                  v-model="ajaxForm.url"
                  style="max-width: 800px"
                  placeholder="请输入视频地址（Please Input Video URL）"
                  class="input-with-select"
                  :disabled="action.disabled"
                  clearable
                  @blur="handleChangeUrl"
                  @change="handleChangeUrl"
                >
                  <template #append>
                    <el-select
                      v-model="ajaxForm.language"
                      placeholder="Select Language"
                      style="width: 145px"
                      @change="(e) => (ajaxForm.language = e)"
                    >
                      <el-option
                        v-for="item in languageList"
                        :label="item.label"
                        :value="item.key"
                        :key="item.key"
                      />
                    </el-select>
                    <el-button
                      type="primary"
                      style="width: 108px"
                      @click="submitForm(formRef)"
                      :loading="action.isLoading"
                      >Confirm</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
            <el-row>
              <el-upload
                v-model:file-list="uploadAction.fileList"
                :action="uploadAction.uploadUrl"
                :headers="uploadAction.headers"
                :limit="1"
                :on-success="uploadFile"
                :on-remove="removeFile"
                accept="video/mp4"
              >
                <el-button type="primary" plain>Upload Video</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    请选择视频并上传（Select and upload video）
                  </div>
                </template>
              </el-upload>
            </el-row>
          </div>
        </client-only>

        <div class="list-body">
          <div class="bd-left">
            <el-table :data="action.list" style="width: 100%" border>
              <el-table-column prop="uri" label="Video URL" width="500" />
              <el-table-column prop="status" label="Status" width="180">
                <template #default="scope"
                  ><el-tag effect="dark" :type="tagType[scope.row.status].type">
                    {{ tagType[scope.row.status].title }}
                  </el-tag></template
                >
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="Create Time"
                width="180"
              />
              <el-table-column
                prop="workTime"
                label="Finish Time"
                width="180"
              />
              <el-table-column label="Option" width="200" fixed="right"
                ><template #default="scope"
                  ><el-button
                    type="primary"
                    link
                    @click="handleOpen(scope.$index)"
                    >查看结果（View Results）</el-button
                  >
                  <el-button
                    type="primary"
                    link
                    @click="reloadItem(scope.row)"
                    v-if="
                      scope.row.status != 'END' && scope.row.status != 'ERROR'
                    "
                    :loading="scope.row.isLoading"
                    >刷新（Refresh）</el-button
                  >

                  <el-popconfirm
                    title="Are you sure delete it？"
                    placement="top-start"
                    @confirm="handleDelete(scope.row)"
                  >
                    <template #reference>
                      <el-button type="danger" link>删除（Delete）</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin-top: 20px; float: right"
              :page-size="action.pageSize"
              :current-page="action.pageNum"
              @update:page-size="handlePageSize"
              @update:current-page="handlePageSize"
              layout="prev, pager, next"
              :total="action.total"
            />
          </div>
        </div>
      </el-main>
    </el-container>
    <el-dialog
      v-model="action.loginDialogVisible"
      title="Login"
      width="500"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :inline="true"
        ref="loginFormRef"
        :model="action.loginForm"
        class="demo-form-inline"
        label-width="100px"
      >
        <el-form-item
          label="UserName"
          prop="userName"
          :rules="[{ required: true, message: 'please input User Name' }]"
        >
          <el-input
            v-model="action.loginForm.userName"
            placeholder="please input User Name"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="Password"
          prop="password"
          :rules="[{ required: true, message: 'please input Password' }]"
        >
          <el-input
            v-model="action.loginForm.password"
            placeholder="please input Password"
            type="password"
            clearable
          />
        </el-form-item>
        <p>
          <el-text
            class="mx-1"
            type="danger"
            v-show="action.errmsg && action.errmsg.length > 2"
            >{{ action.errmsg }}</el-text
          >
        </p>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="action.showQrcode = true">
            试用申请（Request for Trial）
          </el-button>
          <el-button type="primary" @click="login(loginFormRef)">
            Login
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="action.showQrcode" title="Qr Code" width="400">
      <div>Email：zhans52@gmail.com</div>
      <p>&nbsp;</p>
      <div>微信请添加备注：申请试用</div>
      <div><img src="/static/image/qrcode.png" /></div>
    </el-dialog>
    <client-only>
      <el-drawer
        v-model="action.showLine"
        title="视频解析结果（Video Analysis Results）"
        direction="rtl"
        size="50%"
      >
        <ShowItem :data="action.ShowItem"></ShowItem>
      </el-drawer>
    </client-only>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import {
  getAnalysisList,
  addAnalysis,
  getAnalysisItem,
  delAnalysis,
} from "../api/videoAnalysis";
import { Login } from "../api/login";
import { ElMessage } from "element-plus";
import { getToken, isLogin } from "../api/utils/Token";
import { getPointList, getPointItem } from "../api/videoPoint";

import { useRuntimeConfig } from "#app";

const config = useRuntimeConfig(); // 获取运行时配置

let timeout,
  times = 5000;

const formRef = ref();

const loginFormRef = ref();

const ajaxForm = reactive({
  url: "",
  language: "Chinese",
});

const languageList = [
  { label: "中文(简)", key: "Chinese" },
  { label: "Халх монгол", key: "Khalkha_Mongolian" },
  { label: "བོད་ཡིག", key: "Tibetan" },
];

const rules = {
  url: [
    {
      required: true,
      message: "视频地址不能为空（Video URL cannot be empty）",
    },
    {
      validator: (rule, value, callback) => {
        if (
          !value.startsWith("https://www.tiktok.com") &&
          !value.startsWith("https://www.instagram.com") &&
          !value.startsWith("https://www.youtube.com") &&
          !value.startsWith("/profile")
        ) {
          callback(new Error("请输入正确的TikTok/地址或者上传文件"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

const handleChangeUrl = () => {
  ajaxForm.url = ajaxForm.url.trim();
};

const tagType = {
  START: { type: "info", title: "排队中(Queuing)" },
  DOWNLOADING: { type: "primary", title: "下载中(Downloading)" },
  DOWNLOAD: { type: "primary", title: "数据初始化(Initialization)" },
  EXTRACT: { type: "warning", title: "AI解析中(AI Analyzing)" },
  END: { type: "success", title: "完成(Complete)" },
  ERROR: { type: "danger", title: "失败(Failed)" },
};
const action = reactive({
  list: [],
  editNotes: "",
  point: "",
  pointLogs: [],
  loginDialogVisible: false,
  showQrcode: false,
  loginForm: {
    userName: "",
    password: "",
  },
  errmsg: "",
  showLine: false,
  isLoading: false,
  disabled: true,

  ShowItem: {},
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const uploadAction = reactive({
  isLoading: false,
  uploadUrl: config.public.baseURL + "/common/upload/mp4", // 上传的图片服务器地址
  headers: {
    Authorization: "Bearer " + getToken(),
  },
  fileList: [],
});

const submitForm = (formRef) => {
  formRef.validate((valid) => {
    if (valid) {
      action.isLoading = true;
      action.disabled = true;
      addAnalysis(ajaxForm.url, ajaxForm.language)
        .then(() => {
          getList();
          action.isLoading = false;
          action.disabled = false;
          uploadAction.fileList = [];
          formRef.resetFields();
          ElMessage({
            message: "提交成功",
            type: "success",
          });
        })
        .catch((e) => {
          const { msg, code } = e;
          action.isLoading = false;
          action.disabled = false;
          if (code != 401) {
            ElMessage.error(`操作失败:${msg}`);
          }
        });
    }
  });
};

const uploadFile = ({ code, fileName }) => {
  if (code == 200) {
    action.disabled = true;
    ajaxForm.url = fileName;
  }
};

const reloadItem = (item) => {
  item.isLoading = true;
  getAnalysisItem(item.id).then((row) => {
    item.isLoading = false;
    item.status = row.data.status;
    item.content = row.data.content;
    item.workTime = row.data.workTime;
    item.mp4Path = row.data.mp4Path;
  });
};

const showLoginDalog = (value) => {
  action.errmsg = "";
  action.loginDialogVisible = !value;
};

isLogin.on(showLoginDalog);

const getList = (pageNum = 1, pageSize = action.pageSize) => {
  action.isLoading = true;
  action.disabled = true;
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  getAnalysisList({ pageNum, pageSize }).then((json) => {
    action.isLoading = false;
    action.disabled = false;
    const { rows, total } = json;
    action.total = total;
    action.pageNum = pageNum;
    action.list = rows;
    // setTimeoutLine()
    getPointItem().then((json) => {
      action.point = json.data;
    });
    getPointList().then((json) => {
      action.pointLogs = json.rows;
    });
  });
};

if (process.client) {
  onMounted(() => {
    action.isLoading = true;
    getList();
  });
}

const login = (loginFormRef) => {
  action.disabled = true;
  loginFormRef.validate((valid) => {
    if (valid) {
      Login(action.loginForm.userName, action.loginForm.password)
        .then(() => {
          getList();
          isLogin.set(true);
        })
        .catch((e) => {
          action.errmsg = e.msg || "操作失败";
        });
    }
  });
};

const handleOpen = (index) => {
  action.showLine = true;
  action.ShowItem = action.list[index];
};

const tableRowClassName = ({ row, rowIndex }) => {
  const className = tagType[row.status].type;
  return `${className}-row`;
};

const handlePageSize = (pageNum) => {
  getList(pageNum);
};

const removeFile = () => {
  ajaxForm.url = "";
  action.disabled = false;
};

const handleDelete = ({ id }) => {
  action.disabled = true;
  delAnalysis(id).then(() => {
    getList();
    action.disabled = false;
    formRef.resetFields();
    ElMessage({
      message: "提交成功",
      type: "success",
    });
  });
};
</script>
<style lang="scss">
.navbar {
  top: 0;
  left: 0;
  position: relative;
  z-index: 12;
}

@media screen and (min-width: 960px) {
  .navbar {
    position: sticky;
    width: 100%;
  }
}

.navbar-wrapper {
  position: relative;
  border-bottom: 1px solid var(--border-color);
  height: 55px;
  padding: 0 12px 0 24px;
  background-image: radial-gradient(transparent 1px, var(--bg-color) 1px);
  background-size: 4px 4px;
  backdrop-filter: saturate(50%) blur(4px);
  -webkit-backdrop-filter: saturate(50%) blur(4px);
  top: 0;
  display: flex;
  justify-content: space-between;

  .header-container {
    display: flex;
    justify-content: flex-start;

    .web-name {
      font-size: 1rem;
      font-weight: 700;
      margin-bottom: 8px;
      line-height: 55px;
    }

    .web-dis {
      font-size: 0.8rem;
      margin-bottom: 8px;
      line-height: 55px;
      margin-left: 10px;
      color: #00000080;
      align-items: flex-end; /* 垂直居底 */
    }
  }
  .text-gray-light {
    line-height: 55px;
    cursor: pointer;
  }
}

@media screen and (min-width: 1680px) {
  .navbar-wrapper {
    padding: 0 48px;
  }
}

@media screen and (min-width: 1280px) {
  .navbar-wrapper {
    padding: 0 32px;
  }
}
@media screen and (min-width: 768px) {
  .navbar-wrapper {
    padding: 0 12px 0 32px;
  }
}

.page-content {
  outline: none;
  padding: 48px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  width: 100%;
  background-color: #f9fbff;
  .in-input {
    width: 846px;
    margin: auto;
  }
  .list-body {
    width: 100%;
    padding: 18px 0;
    display: flex;
    justify-content: center;

    .bd-left {
      width: 1180px;
    }

    .el-table .warning-row {
      --el-table-tr-bg-color: var(--el-color-warning-light-9);
    }
    .el-table .success-row {
      --el-table-tr-bg-color: var(--el-color-success-light-9);
    }
  }
  .ayns-list {
  }
  .el-input__wrapper {
    box-shadow: none;
    border: 2px solid #c4c7ce;
    border-right-color: #fff;
  }

  .el-form-item.is-error .el-input__wrapper {
    box-shadow: none;
    border: 2px solid red;
    border-right-color: #fff;
    line-height: 44px;
  }
  .el-input {
    height: 44px;
  }

  .el-input-group__append button.el-button {
    width: 108px;
    height: 100%;
    color: #fff;
    background-color: #409eff;
    border-top-left-radius: initial;
    border-bottom-left-radius: initial;
  }
  .el-input-group__append .el-select {
    margin: 0 20px 0 0;
  }
  .el-input-group__append {
    padding: 0 20px 0 0;
  }
  .el-input-group--append
    .el-input-group__append
    .el-select
    .el-select__wrapper {
    height: 43px;
  }

  .el-select__placeholder.is-transparent {
    color: #000000e6;
  }
}

.ayns-list {
  width: 90%;

  .c-title {
    padding-right: 10px;
  }
}

/* 你的样式 */
</style>